package ru.compft.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import ru.compft.web.WebConst;
import ru.compft.web.beans.SystemPropBean;
import ru.compft.web.utils.FacesUtils;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.ServletRequest;
import java.io.Serializable;

/**
 * User: VVasiliev
 * Date: 14.06.12
 * Time: 13:43
 * Контроллер для управления системными свойствами
 */
@ManagedBean(name = WebConst.SYSTEM_PROPS_CONTROLLER)
@ViewScoped
public class SystemPropsController implements Serializable {
    private static final long serialVersionUID = -8963945273468070060L;

    private static final Logger logger = LoggerFactory.getLogger(SystemPropsController.class);
    public static final String BEAN_ID = "beanId";

    private SystemPropBean selectedBean;

    public SystemPropBean getSelectedBean() {
        return selectedBean;
    }

    public void setSelectedBean(SystemPropBean selectedBean) {
        this.selectedBean = selectedBean;
    }

    public void selectAction(AjaxBehaviorEvent actionEvent) {
        System.out.println("AjaxBehaviorEvent = " + actionEvent);
    }

    public void initSelected(ComponentSystemEvent event) {
        System.out.println("ComponentSystemEvent = " + event);
        setSelectedBean(new SystemPropBean());
    }

    public void cancelAction() {
        System.out.println("cancelAction = ");
        setSelectedBean(null);
    }
    /**
     * Редактируем свойство
     */
    public String editSelected() {
        if (logger.isDebugEnabled()) {
            logger.debug("Edit selected property...");
        }

        final ServletRequest servletRequest = (ServletRequest) FacesUtils.getExternalContext().getRequest();
        final String beanId = servletRequest.getParameter(BEAN_ID);

        if(StringUtils.hasText(beanId)){
            if (logger.isDebugEnabled()) {
                logger.debug("Selected property with id = " + beanId);
            }
        }else{
            // todo сделать через файл messages
            FacesUtils.addWarnMessage(null, "Записи не выбраны");
        }
//        beanId
        System.out.println("EDIT ACTION = " + beanId);

        servletRequest.setAttribute("id", beanId);
        return "";
    }
}
